﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.IO;
using MyDiary;

namespace QuickWPFMonthCalendar
{
    /// <summary>
    /// Index.xaml の相互作用ロジック
    /// </summary>
    public partial class Index : Window
    {
        private System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        private bool isEnable = false;
        private int intmonth = 1;
        private List<TextBlock> Listtb = new List<TextBlock>();
        private List<Button> Listedit = new List<Button>();
        private List<Button> Listadd = new List<Button>();
        private List<TextBlock> ListtbInfo = new List<TextBlock>();
        private List<Image> Listimg = new List<Image>();
        private List<Image> Listbgimg = new List<Image>();
        private List<DB.Tables.Diary> Listdiary = new List<DB.Tables.Diary>();
        private List<Container> ListContainer = new List<Container>();
        private DB.Tables.Settings Settings = new DB.Tables.Settings();

        private List<int> RotateImage = new List<int>();

        public Index()
        {
            InitializeComponent();


            Appointment app = new Appointment();



            isEnable = false;

            string srtYear = DateTime.Today.ToString("yyyy");

            DateTime getDate = (DateTime.Parse(srtYear += "/01/01"));


            List<string> months = new List<string>();

            for (int i = 1; i <= 12; i++)
            {
                months.Add(getDate.ToString("MMMM"));
                getDate = getDate.AddMonths(1);
            }

            cboMonth.ItemsSource = months;

            for (int i = -50; i < 50; i++)
            {
                cboYear.Items.Add(DateTime.Today.AddYears(i).Year);
            }
            string mont = DateTime.Today.ToString("MMMM");
            cboMonth.SelectedItem = months.FirstOrDefault(w => w == mont);
            cboYear.SelectedItem = DateTime.Today.Year;

            inicia();

            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
            dispatcherTimer.Start();

            isEnable = true;
        }

        /// <summary>
        /// clear list
        /// </summary>
        private void clearList()
        {

            Listtb = new List<TextBlock>();

            Listedit = new List<Button>();
            Listadd = new List<Button>();
            ListtbInfo = new List<TextBlock>();
            Listimg = new List<Image>();
            Listdiary = new List<DB.Tables.Diary>();
            ListContainer = new List<Container>();

            RotateImage = new List<int>();


        }

        /// <summary>
        /// inicial object
        /// </summary>
        private void inicia()
        {
            GetSettings();

            AddTb();



            int year = (int)cboYear.SelectedItem;

            int month = cboMonth.SelectedIndex + 1;

            DateTime dt = new DateTime(year, month, 1);



            foreach (TextBlock tb in Listtb)
            {
                tb.Text = string.Empty;
            }

            foreach (Button tb in Listedit)
            {
                tb.Visibility = Visibility.Hidden;
            }

            foreach (Button tb in Listadd)
            {
                tb.Visibility = Visibility.Hidden;
            }



            intmonth = int.Parse(dt.DayOfWeek.ToString("d")) + 1;

            int day = 1;


            for (int i = intmonth; i <= int.Parse(dt.AddMonths(1).AddDays(-1).Day.ToString("d")); i++)
            {
                foreach (TextBlock tb in Listtb)
                    if (tb.Name.Equals("tb_" + i.ToString()))
                    {
                        tb.Text = day.ToString();

                        foreach (Image bg in Listbgimg)
                            if (bg.Name.Equals("bgimg_" + i.ToString()))
                            {

                                if (DateTime.Now.ToString("yyyy/MM/d").Equals(dt.ToString("yyyy/MM/") + day.ToString()))
                                    bg.Source = returnImageBib(string.Format("/MyDiary;component/Images/{0}today.jpg", Settings.color));
                                else
                                    bg.Source = returnImageBib(string.Format("/MyDiary;component/Images/{0}.jpg", Settings.color));

                            }

                        day++;
                    }

                foreach (Button tb in Listedit)
                    if (tb.Name.Equals("edit_" + i.ToString()))
                    {
                        // tb.Visibility = Visibility.Visible;
                    }

                foreach (Button tb in Listadd)
                    if (tb.Name.Equals("add_" + i.ToString()))
                    {
                        tb.Visibility = Visibility.Visible;
                    }


            }

            RefreshCalendar();

        }


        private void SelectedCalendar()
        {
            isEnable = false;
            RefreshCalendar();
            isEnable = true;
        }

        /// <summary>
        /// refresh deta
        /// </summary>
        private void RefreshCalendar()
        {
            if (cboYear.SelectedItem == null) return;
            if (cboMonth.SelectedItem == null) return;

            int year = (int)cboYear.SelectedItem;

            int month = cboMonth.SelectedIndex + 1;

            DateTime targetDate = new DateTime(year, month, 1);

            DB.Execute execute = new DB.Execute();
            DataSet ds = execute.Select_tblBody();



            foreach (DataTable dt in ds.Tables)
                foreach (DataRow dr in dt.Rows)
                {
                    string srtselected = targetDate.ToString("yyyy/MM");
                    string strdb = dr["DateFormat"].ToString();

                    if (!string.IsNullOrEmpty(strdb))
                    {
                        strdb = DateTime.Parse(strdb).ToString("yyyy/MM");
                        if (strdb.Equals(srtselected))
                        {

                            DB.Tables.Diary Item = new DB.Tables.Diary()
                            {
                                DateFormat = dr["DateFormat"].ToString(),
                                Body = dr["Body"].ToString(),
                                Id = dr["Id"].ToString()
                            };

                            Listdiary.Add(Item);

                            for (int i = 1; i <= 35; i++)
                            {

                                foreach (TextBlock tb in Listtb)
                                {

                                    if (tb.Text.Equals(i.ToString()))
                                    {
                                        DateTime datetime = DateTime.Parse(Item.DateFormat);
                                        string[] split = tb.Name.Split('_');
                                        if (i.Equals(datetime.Day))
                                            foreach (TextBlock tbInfo in ListtbInfo)
                                                if (tbInfo.Name.Equals("tbInfo_" + split[1]))
                                                {
                                                    tbInfo.Text = Item.Body;

                                                    foreach (Button edit in Listedit)
                                                        if (edit.Name.Equals("edit_" + split[1]))
                                                        {
                                                            edit.Visibility = Visibility.Visible;
                                                        }

                                                    foreach (Button add in Listadd)
                                                        if (add.Name.Equals("add_" + split[1]))
                                                        {
                                                            add.Visibility = Visibility.Hidden;
                                                        }
                                                }
                                    }

                                }
                            }

                        }
                    }
                }


            foreach (DB.Tables.Diary diary in Listdiary)
            {

                ds = execute.Select_tblImages(int.Parse(diary.Id));
                List<DB.Tables.Images> ListImages = new List<DB.Tables.Images>();

                foreach (DataTable dt in ds.Tables)
                    foreach (DataRow dr in dt.Rows)
                    {

                        DB.Tables.Images itemImages = new DB.Tables.Images()
                        {

                            Path = dr["Path"].ToString(),
                            Id_diary = dr["Id_diary"].ToString(),
                            Id = dr["Id"].ToString()
                        };

                        ListImages.Add(itemImages);

                    }

                if (ListImages.Count > 0)
                {

                    ListContainer.Add(new Container()
                    {
                        Diary = diary,
                        listImages = ListImages
                    });
                }
                else
                {
                    ListContainer.Add(new Container()
                    {
                        Diary = diary,
                        listImages = new List<DB.Tables.Images>()
                    });
                }

            }

            changeImage();

        }

        //private void Calendar_DayChanged(object sender, DayChangedEventArgs e)
        //{
        //    if (isEnable) return;

        //    if (!string.IsNullOrEmpty(e.Day.Id))
        //    {

        //        DB.Execute execute = new DB.Execute();
        //        DataSet ds = execute.Select_tblBody(int.Parse(e.Day.Id));
        //        DB.Tables.Diary DiaryItem = new DB.Tables.Diary();


        //        foreach (DataTable dt in ds.Tables)
        //            foreach (DataRow dr in dt.Rows)
        //            {


        //                DiaryItem.DateFormat = dr["DateFormat"].ToString();
        //                DiaryItem.Body = dr["Body"].ToString();
        //                DiaryItem.Id = dr["Id"].ToString();



        //            }


        //        ds = execute.Select_tblImages(int.Parse(e.Day.Id));
        //        List<DB.Tables.Images> ListImages = new List<DB.Tables.Images>();

        //        foreach (DataTable dt in ds.Tables)
        //            foreach (DataRow dr in dt.Rows)
        //            {

        //                DB.Tables.Images itemImages = new DB.Tables.Images()
        //                {

        //                    Path = dr["Path"].ToString(),
        //                    Id_diary = dr["Id_diary"].ToString(),
        //                    Id = dr["Id"].ToString()
        //                };

        //                ListImages.Add(itemImages);

        //            }



        //        viewDiary viewdiary = new viewDiary(DiaryItem, ListImages);

        //        viewdiary.ShowDialog();
        //    }
        //    else
        //    {

        //        Create create = new Create();

        //        create.ShowDialog();
        //    }
        //    SelectedCalendar();
        //    //save the text edits to persistant storage
        //}


        //  System.Windows.Threading.DispatcherTimer.Tick handler
        //
        //  Updates the current seconds display and calls
        //  InvalidateRequerySuggested on the CommandManager to force 
        //  the Command to raise the CanExecuteChanged event.
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            changeImage();
        }
        private void changeImage()
        {
            foreach (Container cont in ListContainer)
                for (int i = 1; i <= 35; i++)
                {
                    if (cont.listImages.Count > 0)
                        foreach (TextBlock tb in Listtb)
                        {
                            if (tb.Text.Equals(i.ToString()))
                            {
                                DateTime datetime = DateTime.Parse(cont.Diary.DateFormat);
                                string[] split = tb.Name.Split('_');
                                if (i.Equals(datetime.Day))
                                    foreach (Image img in Listimg)
                                        if (img.Name.Equals("img_" + split[1]))
                                        {
                                            int j = RotateImage[int.Parse(split[1])];

                                            if ((j + 1) < cont.listImages.Count)
                                            {
                                                j++;

                                            }
                                            else
                                            {
                                                j = 0;

                                            }

                                            img.Source = returnImage(cont.listImages[j].Path);
                                            RotateImage[int.Parse(split[1])] = j;
                                        }
                            }

                        }
                }


        }

        protected BitmapImage returnImage(string path)
        {
            string dicpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            Uri uri = new Uri(dicpath + @"\" + path, UriKind.RelativeOrAbsolute);
            bitImage.UriSource = uri;
            bitImage.EndInit();

            return bitImage;
        }

        protected BitmapImage returnImageBib(string path)
        {

            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);
            bitImage.UriSource = uri;
            bitImage.EndInit();

            return bitImage;
        }

        private void cbo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isEnable)
            {
                clearList();
                inicia();
                RefreshCalendar();
            }
        }

        /// <summary>
        /// create object
        /// </summary>
        private void AddTb()
        {
            Listtb.Add(tb_1);
            Listtb.Add(tb_2);
            Listtb.Add(tb_3);
            Listtb.Add(tb_4);
            Listtb.Add(tb_5);
            Listtb.Add(tb_6);
            Listtb.Add(tb_7);
            Listtb.Add(tb_8);
            Listtb.Add(tb_9);
            Listtb.Add(tb_10);
            Listtb.Add(tb_11);
            Listtb.Add(tb_12);
            Listtb.Add(tb_13);
            Listtb.Add(tb_14);
            Listtb.Add(tb_15);
            Listtb.Add(tb_16);
            Listtb.Add(tb_17);
            Listtb.Add(tb_18);
            Listtb.Add(tb_19);
            Listtb.Add(tb_20);
            Listtb.Add(tb_21);
            Listtb.Add(tb_22);
            Listtb.Add(tb_23);
            Listtb.Add(tb_24);
            Listtb.Add(tb_25);
            Listtb.Add(tb_26);
            Listtb.Add(tb_27);
            Listtb.Add(tb_28);
            Listtb.Add(tb_29);
            Listtb.Add(tb_30);
            Listtb.Add(tb_31);
            Listtb.Add(tb_32);
            Listtb.Add(tb_33);
            Listtb.Add(tb_34);
            Listtb.Add(tb_35);

            Listedit.Add(edit_1);
            Listedit.Add(edit_2);
            Listedit.Add(edit_3);
            Listedit.Add(edit_4);
            Listedit.Add(edit_5);
            Listedit.Add(edit_6);
            Listedit.Add(edit_7);
            Listedit.Add(edit_8);
            Listedit.Add(edit_9);
            Listedit.Add(edit_10);
            Listedit.Add(edit_11);
            Listedit.Add(edit_12);
            Listedit.Add(edit_13);
            Listedit.Add(edit_14);
            Listedit.Add(edit_15);
            Listedit.Add(edit_16);
            Listedit.Add(edit_17);
            Listedit.Add(edit_18);
            Listedit.Add(edit_19);
            Listedit.Add(edit_20);
            Listedit.Add(edit_21);
            Listedit.Add(edit_22);
            Listedit.Add(edit_23);
            Listedit.Add(edit_24);
            Listedit.Add(edit_25);
            Listedit.Add(edit_26);
            Listedit.Add(edit_27);
            Listedit.Add(edit_28);
            Listedit.Add(edit_29);
            Listedit.Add(edit_30);
            Listedit.Add(edit_31);
            Listedit.Add(edit_32);
            Listedit.Add(edit_33);
            Listedit.Add(edit_34);
            Listedit.Add(edit_35);


            Listadd.Add(add_1);
            Listadd.Add(add_2);
            Listadd.Add(add_3);
            Listadd.Add(add_4);
            Listadd.Add(add_5);
            Listadd.Add(add_6);
            Listadd.Add(add_7);
            Listadd.Add(add_8);
            Listadd.Add(add_9);
            Listadd.Add(add_10);
            Listadd.Add(add_11);
            Listadd.Add(add_12);
            Listadd.Add(add_13);
            Listadd.Add(add_14);
            Listadd.Add(add_15);
            Listadd.Add(add_16);
            Listadd.Add(add_17);
            Listadd.Add(add_18);
            Listadd.Add(add_19);
            Listadd.Add(add_20);
            Listadd.Add(add_21);
            Listadd.Add(add_22);
            Listadd.Add(add_23);
            Listadd.Add(add_24);
            Listadd.Add(add_25);
            Listadd.Add(add_26);
            Listadd.Add(add_27);
            Listadd.Add(add_28);
            Listadd.Add(add_29);
            Listadd.Add(add_30);
            Listadd.Add(add_31);
            Listadd.Add(add_32);
            Listadd.Add(add_33);
            Listadd.Add(add_34);
            Listadd.Add(add_35);


            ListtbInfo.Add(tbInfo_1);
            ListtbInfo.Add(tbInfo_2);
            ListtbInfo.Add(tbInfo_3);
            ListtbInfo.Add(tbInfo_4);
            ListtbInfo.Add(tbInfo_5);
            ListtbInfo.Add(tbInfo_6);
            ListtbInfo.Add(tbInfo_7);
            ListtbInfo.Add(tbInfo_8);
            ListtbInfo.Add(tbInfo_9);
            ListtbInfo.Add(tbInfo_10);
            ListtbInfo.Add(tbInfo_11);
            ListtbInfo.Add(tbInfo_12);
            ListtbInfo.Add(tbInfo_13);
            ListtbInfo.Add(tbInfo_14);
            ListtbInfo.Add(tbInfo_15);
            ListtbInfo.Add(tbInfo_16);
            ListtbInfo.Add(tbInfo_17);
            ListtbInfo.Add(tbInfo_18);
            ListtbInfo.Add(tbInfo_19);
            ListtbInfo.Add(tbInfo_20);
            ListtbInfo.Add(tbInfo_21);
            ListtbInfo.Add(tbInfo_22);
            ListtbInfo.Add(tbInfo_23);
            ListtbInfo.Add(tbInfo_24);
            ListtbInfo.Add(tbInfo_25);
            ListtbInfo.Add(tbInfo_26);
            ListtbInfo.Add(tbInfo_27);
            ListtbInfo.Add(tbInfo_28);
            ListtbInfo.Add(tbInfo_29);
            ListtbInfo.Add(tbInfo_30);
            ListtbInfo.Add(tbInfo_31);
            ListtbInfo.Add(tbInfo_32);
            ListtbInfo.Add(tbInfo_33);
            ListtbInfo.Add(tbInfo_34);
            ListtbInfo.Add(tbInfo_35);




            Listimg.Add(img_1);
            Listimg.Add(img_2);
            Listimg.Add(img_3);
            Listimg.Add(img_4);
            Listimg.Add(img_5);
            Listimg.Add(img_6);
            Listimg.Add(img_7);
            Listimg.Add(img_8);
            Listimg.Add(img_9);
            Listimg.Add(img_10);
            Listimg.Add(img_11);
            Listimg.Add(img_12);
            Listimg.Add(img_13);
            Listimg.Add(img_14);
            Listimg.Add(img_15);
            Listimg.Add(img_16);
            Listimg.Add(img_17);
            Listimg.Add(img_18);
            Listimg.Add(img_19);
            Listimg.Add(img_20);
            Listimg.Add(img_21);
            Listimg.Add(img_22);
            Listimg.Add(img_23);
            Listimg.Add(img_24);
            Listimg.Add(img_25);
            Listimg.Add(img_26);
            Listimg.Add(img_27);
            Listimg.Add(img_28);
            Listimg.Add(img_29);
            Listimg.Add(img_30);
            Listimg.Add(img_31);
            Listimg.Add(img_32);
            Listimg.Add(img_33);
            Listimg.Add(img_34);
            Listimg.Add(img_35);



            Listbgimg.Add(bgimg_1);
            Listbgimg.Add(bgimg_2);
            Listbgimg.Add(bgimg_3);
            Listbgimg.Add(bgimg_4);
            Listbgimg.Add(bgimg_5);
            Listbgimg.Add(bgimg_6);
            Listbgimg.Add(bgimg_7);
            Listbgimg.Add(bgimg_8);
            Listbgimg.Add(bgimg_9);
            Listbgimg.Add(bgimg_10);
            Listbgimg.Add(bgimg_11);
            Listbgimg.Add(bgimg_12);
            Listbgimg.Add(bgimg_13);
            Listbgimg.Add(bgimg_14);
            Listbgimg.Add(bgimg_15);
            Listbgimg.Add(bgimg_16);
            Listbgimg.Add(bgimg_17);
            Listbgimg.Add(bgimg_18);
            Listbgimg.Add(bgimg_19);
            Listbgimg.Add(bgimg_20);
            Listbgimg.Add(bgimg_21);
            Listbgimg.Add(bgimg_22);
            Listbgimg.Add(bgimg_23);
            Listbgimg.Add(bgimg_24);
            Listbgimg.Add(bgimg_25);
            Listbgimg.Add(bgimg_26);
            Listbgimg.Add(bgimg_27);
            Listbgimg.Add(bgimg_28);
            Listbgimg.Add(bgimg_29);
            Listbgimg.Add(bgimg_30);
            Listbgimg.Add(bgimg_31);
            Listbgimg.Add(bgimg_32);
            Listbgimg.Add(bgimg_33);
            Listbgimg.Add(bgimg_34);
            Listbgimg.Add(bgimg_35);

            foreach (Image tb in Listbgimg)
            {
                tb.Source = returnImageBib(string.Format("/MyDiary;component/Images/{0}.jpg", Settings.color));
            }


            for (int i = 0; i < 35; i++)
                RotateImage.Add(0);


            foreach (TextBlock tb in Listtb)
                tb.Text = string.Empty;



            foreach (TextBlock tb in ListtbInfo)
            {
                tb.Text = string.Empty;
                tb.MouseDown -= new MouseButtonEventHandler(view_MouseDown);

                tb.MouseDown += new MouseButtonEventHandler(view_MouseDown);
            }
            foreach (Image tb in Listimg)
                tb.Source = null;

        }

        /// <summary>
        /// evento view double clic
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void view_MouseDown(object sender, MouseButtonEventArgs e)
        {

            if (e.ClickCount == 2)
            {
                TextBlock tbClick = (TextBlock)sender;
                string[] splitClick = tbClick.Name.Split('_');
                TextBlock tb = Listtb[int.Parse(splitClick[1]) - 1];
                Container result = new Container();
                bool isHave = false;

                foreach (Container cont in ListContainer)
                    for (int i = 1; i <= 35; i++)
                    {

                        if (tb.Text.Equals(i.ToString()))
                        {
                            DateTime datetime = DateTime.Parse(cont.Diary.DateFormat);
                            string[] split = tb.Name.Split('_');

                            if (tb.Text.Equals(datetime.Day.ToString()))
                            {
                                result = cont;
                                isHave = true;
                                break;
                            }
                        }


                    }



                if (isHave)
                {

                    viewDiary viewdiary = new viewDiary(result.Diary, result.listImages);

                    viewdiary.ShowDialog();

                }
            }


        }

        /// <summary>
        /// add or edit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void click_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            string[] split = btn.Name.Split('_');

            int year = (int)cboYear.SelectedItem;

            int month = cboMonth.SelectedIndex + 1;




            if (split[0].Equals("add") || split[0].Equals("edit"))
            {

                DateTime dt = DateTime.Now;
                foreach (TextBlock tb in Listtb)
                    if (tb.Name.Equals("tb_" + split[1].ToString()))
                    {
                        dt = new DateTime(year, month, int.Parse(tb.Text));

                        break;
                    }
                Create create = new Create(dt.ToString("yyyy/MM/dd"));
                create.ShowDialog();
            }
            else
            {
                //viewDiary viewdiary = new viewDiary(DiaryItem, ListImages);
                //viewdiary.ShowDialog();
            }
            clearList();
            inicia();
            SelectedCalendar();
        }


        private void click_Setting(object sender, RoutedEventArgs e)
        {
            gridSetting.Visibility = gridSetting.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
        }

        /// <summary>
        /// setting update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void click_SettingColor(object sender, RoutedEventArgs e)
        {
            Button bt = (Button)sender;

            string[] spColor = bt.Name.Split('_');

            this.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(spColor[1]));

            foreach (Image tb in Listbgimg)
            {
                tb.Source = returnImageBib(string.Format("/QuickWPFMonthCalendar;component/Images/{0}.jpg", spColor[1]));
            }

            Settings.color = spColor[1];
            DB.Execute execute = new DB.Execute();
            execute.Update_tblSettings(Settings);

            clearList();
            inicia();
            SelectedCalendar();
        }


        /// <summary>
        /// get settings
        /// </summary>
        private void GetSettings()
        {

            DB.Execute execute = new DB.Execute();
            DataSet ds = execute.Select_tblSettings();
            foreach (DataTable dt in ds.Tables)
                foreach (DataRow dr in dt.Rows)
                    if (dr["Id"].ToString().ToUpper().Equals("COLOR"))
                        Settings.color = dr["value"].ToString();

            this.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.color));
        }

        /// <summary>
        /// setting update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void click_Information(object sender, RoutedEventArgs e)
        {
            Information viewdiary = new Information();

            viewdiary.ShowDialog();
        }

    }
}
